﻿using BlogManager.Models;
using BlogManager.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace BlogManager.Controllers
{
    public class PostsController : ApiController
    {
        private IPostRepository repository;

        public PostsController()
        {
            repository = new PostRepository();
        }

        public List<Post> Get()
        {
            return repository.GetAll();
        }

        public Post Get(int id)
        {
            Post item = repository.Get(id);
            if (item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return item;
        }

        public HttpResponseMessage Post(Post post)
        {
            repository.Add(post);

            var response = Request.CreateResponse<Post>(System.Net.HttpStatusCode.Created, post);

            return response;
        }

        public void Put(int id, Post post)
        {
            post.Id = id;
            if (!repository.Update(post))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        public void Delete(int id)
        {
            Post item = repository.Get(id);
            if (item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            repository.Remove(id);
        }
    }
}
